<template>
  <div class="goods-detail-content"
       v-if="goodsInfo">

    <!-- 轮播图 -->
    <div class="banner">
      <swiper :options="bannerSwiperOption">
        <swiper-slide v-for="(item,index) in goodsInfo.photos"
                      :key="'ad_'+productId+'_'+index"
                      class="banner-item">
          <img class="banner-img"
               :src="item">
        </swiper-slide>
      </swiper>
      <div class="banner-pagination"></div>
    </div>

    <!-- 商品名称，价格信息 -->
    <div class="goods-info">
      <div class="floor name-floor flex">
        <div class="goods-name ellipsis-2 flex-sub">
          <!-- <span v-if="countdownInfo"
                class="goods-name-tag">秒杀</span> -->
          <span>{{goodsInfo.goods_name}}</span>
        </div>
        <!-- <div class="collect"
             @click="productLike">
          <van-icon class="like-icon full"
                    v-if="isFavorate"
                    name="like" />
          <van-icon class="like-icon"
                    v-else
                    name="like-o" />
          <div class="desc">关注</div>
        </div> -->
      </div>
      <div class="floor price-floor flex">
        <div class="text-price main-price">{{goodsInfo.goods_price}}</div>
        <div class="del-price">￥{{goodsInfo.goods_marketprice}}</div>
      </div>
    </div>

    <!-- 商品操作 -->
    <div class="menu-list goods-ma-top">
      <div class="menu-item"
           @click="toggleSkuPop('all')">
        <div class="label">已选数量</div>
        <div class="flex-sub content pick-info">{{goodsNum}}件</div>
        <van-icon name="arrow"
                  class="right-icon" />
      </div>
      <div class="menu-item">
        <div class="label">运费</div>
        <div class="content flex-sub">包邮</div>
      </div>
      <!-- <div class="menu-item"
           v-if="save_money">
        <div class="label">自购省钱</div>
        <div class="content flex-sub text-price">{{save_money}}</div>
      </div>
      <div class="menu-item"
           v-if="enjoy_reward">
        <div class="label">VIP分享赚钱</div>
        <div class="content flex-sub text-price">{{enjoy_reward}}</div>
      </div> -->
    </div>

    <!-- 店铺信息 -->
    <div class="store-info goods-ma-top">
      <div class="floor store-detail flex align-center">
        <img class="store-logo"
             :src="storeInfo.store_logo" />
        <div class="store-name">{{storeInfo.store_name}}</div>
      </div>
      <div class="floor evaluation flex justify-between">
        <div class="equal">
          <span>描述相符</span>
          <span>{{storeInfo.store_credit.store_servicecredit.credit}}</span>
        </div>
        <div class="equal">
          <span>服务态度</span>
          <span>{{storeInfo.store_credit.store_desccredit.credit}}</span>
        </div>
        <div class="equal">
          <span>发货速度</span>
          <span>{{storeInfo.store_credit.store_deliverycredit.credit}}</span>
        </div>
      </div>
    </div>

    <!-- 图文详情 -->
    <div class="graphic-details goods-ma-top"
         v-if="goodsInfo.goods_body">
      <div class="title">图文详情</div>
      <div class="content"
           v-html="goodsInfo.goods_body"></div>
    </div>

    <!-- 底部提示 -->
    <page-bottom :more="false"
                 no-more-text="已经拉到底了"></page-bottom>

    <!-- 底部购买按钮 -->
    <div class="footer">
      <div class="fixed-footer">
        <div class="action"
             @click="$router.push({name:'HomeIndex',query:{id:storeInfo.store_id}})">
          <div class="action-icon">
            <img src="@/assets/image/goods-home.png"
                 class="" />
          </div>
          <div class="action-text">首页</div>
        </div>
        <!-- <div class="action"
             @click="$router.push({ name: 'HomeCart', query:{id:storeInfo.store_id,}, params: { type: 0 } })">
          <div class="action-icon">
            <img src="@/assets/image/goods-cart.png"
                 class="" />
            <div class="tag"
                 v-show="cart_count > 0">{{cart_count}}</div>
          </div>
          <div class="action-text">购物车</div>
        </div> -->
        <van-button v-if="is_cart === 1"
                    class="btn flex-sub cart-btn"
                    block
                    @click="toggleSkuPop('addCart')">加入购物车</van-button>
        <van-button class="btn flex-sub"
                    block
                    @click="toggleSkuPop('buyNow')"
                    :disabled="buyNowBtnDisable.disabled">{{buyNowBtnDisable.btnText}}</van-button>
      </div>
    </div>

    <!-- sku信息 -->
    <goods-sku v-model="popSku"
               :goodsInfo="goodsInfo"
               :showAddCart="showAddCart"
               :showBuyNow="showBuyNow"
               :goodsNum="goodsNum"
               @clickSkuItem="clickSku"
               @updateNum="updateNum"
               @addCart="addCart"
               @buyNow="buyNow"
               v-if="goodsInfo">
    </goods-sku>

  </div>
</template>

<script>
import { Toast } from 'vant'
import { getGoodsInfo } from '@/api/goodsDetail'
import { mapState } from 'vuex'
import PageBottom from '@/components/PageBottom'
import GoodsSku from '@/components/GoodsSku'
import { addCart, cartQuantity } from '@/api/cart'
export default {
  name: 'GoodsDetail',
  data() {
    return {
      productId: this.$route.query.goods_id || null, // 当前的商品ID
      bannerSwiperOption: Object.freeze({
        // 轮播图配置
        pagination: {
          el: '.banner-pagination',
          type: 'fraction'
        },
        autoplay: true,
        loop: true
      }),
      goodsInfo: null, // 商品信息 goodsInfo.goods_type： 100普通商品  101分红商品  102-499商品  103小礼包商品
      storeInfo: null, // 店铺信息
      isFavorate: null, // 是否收藏
      mbBody: null, // 图文
      spec_list: null, // sku列表
      popSku: false, // 是否显示sku弹窗
      showBuyNow: true, // sku显示立即购买
      showAddCart: true, // sku显示加入购物车
      goodsNum: 1, // 选择购买的数量
      cart_count: 0, // 购物车数量
      goods_commend_list: [], // 推荐商品
      is_cart: 0, // 是否可以加入购物车 1 允许 0 不允许
      shareCode: this.$route.query.shareCode || null // 推荐人ID 用于判断小礼品是否可以够买
    }
  },
  created() {
    if (!this.productId) {
      this.$toast({
        type: 'fail',
        message: '商品不存在',
        duration: 3000,
        onClose: () => {
          this.$router.go(-1)
        }
      })
    } else {
      this.queryGoodsInfo()
    }
  },
  components: {
    PageBottom,
    GoodsSku
  },
  computed: {
    ...mapState({
      token: state => state.user.token, // 用户登陆信息
      user: state => state.user.info
    }),

    /**
     * 获取立即购买按钮的状态
     */
    buyNowBtnDisable() {
      let res = { disabled: false, btnText: '立即购买' }
      // 如果商品进入的是小礼品
      if (this.goodsInfo && this.goodsInfo.goods_type === 103) {
        if (!this.shareCode) {
          res = { disabled: true, btnText: '该商品不能直接购买' }
        } else {
          res.btnText = '立即领取'
        }
      }
      return res
    }
  },
  methods: {
    /**
     * 查询商品信息
     */
    queryGoodsInfo() {
      Toast.loading('加载中')
      let extra = {}
      if (this.bargain_id) {
        extra['bargain_id'] = this.bargain_id
      }

      getGoodsInfo(this.productId, this.token, extra)
        .then(res => {
          Toast.clear()
          if (res.result.goods_image) {
            // 处理图片
            var imgList = res.result.goods_image.split(',')
            res.result.goods_info.photos = imgList

            // 页面赋值
            this.goodsInfo = res.result.goods_info
            this.storeInfo = res.result.store_info
            this.isFavorate = res.result.is_favorate
            this.mbBody = res.result.mb_body
            this.spec_list = res.result.spec_list
            this.save_money = res.result.save_money
            this.is_cart = res.result.is_cart // 是否可以加入购物车
            // this.goods_commend_list = res.result.goods_commend_list // 推荐商品
            // this.enjoy_reward = res.result.enjoy_reward
          }
        })
        .catch(res => {
          Toast.clear()
          this.$toast({
            type: 'fail',
            message: res.message
          })
        })
    },

    /**
     * 点击某一项sku
     * @param skuInfo 点击的sku信息
     * @param skuInfo.index 当前点击的sku对应的商品ID
     * @param skuInfo.specList 获取SKU的集合，用于获取对应规格的商品ID
     */
    clickSku({ index, specList }) {
      Object.keys(specList).some(k => {
        // 先移除当前选中的sku规格
        if (typeof this.goodsInfo.goods_spec[k] !== 'undefined') {
          delete this.goodsInfo.goods_spec[k] // 删除当前选中的sku
          this.goodsInfo.goods_spec[index] = specList[index]
          return true
        }
      })
      // 当前的SKU集合（根据每个SKU的ID。找到对应的商品ID）
      let specIndex = Object.keys(this.goodsInfo.goods_spec)
        .sort()
        .join('|')
      this.productId = this.spec_list[specIndex] // 记录当前的skuID对应的商品id
      // 根据选择的skuId对应的商品id重新请求页面接口
      this.queryGoodsInfo()
      // history.replaceState(
      //   { goods_id: this.productId },
      //   'goods_id',
      //   `?goods_id=${this.productId}`
      // )
    },

    /**
     * 更新数量
     */
    updateNum(value) {
      this.goodsNum = value
    },

    /**
     * 加入购物车
     */
    addCart() {
      if (this.goodsInfo.goods_storage < this.goodsNum) {
        this.$toast({
          message: `库存不足，剩余:${this.goodsInfo.goods_storage}件`,
          type: 'loading'
        })
        return false
      }
      addCart(this.productId, this.goodsNum)
        .then(res => {
          Toast.success('操作成功')
          // 查询购物车数量
          cartQuantity()
            .then(res => {
              this.cart_count = res.result.cart_count
            })
            .catch(res => {})
        })
        .catch(res => {
          Toast(res.message)
        })
    },

    /**
     * 立即购买-单独购买
     */
    buyNow() {
      if (this.goodsInfo.goods_storage < this.goodsNum) {
        this.$toast({
          type: 'loading',
          message: `库存不足，剩余:${this.goodsInfo.goods_storage}件`
        })
        return false
      }
      let params = { buy_now: 1, cart_id: `${this.productId}|${this.goodsNum}` }
      // 添加分享人ID
      this.shareCode && (params.shareCode = this.shareCode)
      if (this.token) {
        this.$router.push({ name: 'MakeOrder', query: params })
      } else {
        Toast({
          message: '请先登录',
          duration: 2000,
          type: 'loading',
          onClose: () => {
            this.$router.push({ name: 'HomeLogin' })
          }
        })
      }
    },

    // 显示sku弹窗
    toggleSkuPop(type) {
      switch (type) {
        case 'all':
          this.showAddCart = this.is_cart === 1
          this.showBuyNow = !this.buyNowBtnDisable.disabled
          break
        case 'buyNow':
          this.showAddCart = false
          this.showBuyNow = !this.buyNowBtnDisable.disabled
          break
        case 'addCart':
          this.showAddCart = true
          this.showBuyNow = false
          break
      }

      this.popSku = true
    }
  }
}
</script>

<style lang="scss">
.goods-detail-content {
  // 商品统一的向上间隔
  .goods-ma-top {
    margin-top: 8px;
  }
  // 商品轮播图
  .banner {
    width: 100%;
    height: 100vw;
    position: relative;
    overflow: hidden;
    .banner-item {
      width: 100%;
      height: 100%;
      .banner-img {
        width: 100%;
        height: 100%;
      }
    }
    // 分页器
    .banner-pagination {
      position: absolute;
      left: auto;
      right: 10px;
      bottom: 15px;
      color: #ffffff;
      z-index: 100;
      background-color: rgba(0, 0, 0, 0.5);
      width: 44px;
      height: 22px;
      border-radius: 11px;
      text-align: center;
      line-height: 22px;
      font-size: 11px;
    }
  }

  // 商品信息
  .goods-info {
    background-color: #ffffff;
    padding: 14px 10px;

    .floor + .floor {
      margin-top: 14px;
    }

    // 商品名称
    .goods-name {
      font-size: 14px;
      color: #38373d;
      width: 265px;
      // 预留给收藏按钮的样式
      // max-width: 265px;
      // margin-right: 25px;
      .goods-name-tag {
        font-size: 12px;
        color: #ffffff;
        background: linear-gradient(180deg, #fc6919 0%, #fa4116 100%);
        max-width: 32px;
        text-align: center;
        max-height: 15px;
        line-height: 15px;
        font-weight: normal;
        padding: 0 5px;
        border-radius: 7.5px;
        margin-right: 10px;
      }
    }

    // 收藏按钮
    .collect {
      height: 40px;
      text-align: center;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      color: #999999;
      width: 74px;
      padding-left: 10px;
      position: relative;
      &::after {
        position: absolute;
        content: '';
        width: 1px;
        height: 20px;
        transform: scaleX(0.5) translateY(-50%);
        background-color: #cccccc;
        top: 50%;
        left: 0;
      }
      .like-icon {
        font-size: 19px;
        color: #999999;
        margin-bottom: 5px;
        &.full {
          color: #e9533e;
        }
      }
    }

    // 价格信息
    .price-floor {
      align-items: baseline;
      .main-price {
        color: $mainColor;
        font-size: 16px;
        font-weight: bold;
        margin-right: 5px;
      }
      .del-price {
        color: #a2a2a2;
        font-size: 12px;
        text-decoration: line-through;
      }
    }
  }

  // 商品操作信息
  .menu-list {
    width: 100%;
    padding: 0 10px;
    background-color: #ffffff;
    .menu-item {
      width: 100%;
      height: 43px;
      display: flex;
      align-items: center;
      .label {
        color: #333333;
        font-size: 14px;
      }
      .content {
        margin: 0 5px;
        text-align: right;
        font-size: 14px;
      }
      // .pick-info {
      //   color: $mainColor;
      // }
      .right-icon {
        color: #999999;
        font-size: 14px;
      }
    }
    .menu-item + .menu-item {
      position: relative;
      &::after {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        height: 1px;
        width: 100%;
        background-color: #e5e5e5;
        transform: scaleY(0.5);
      }
    }
  }

  // 店铺信息
  .store-info {
    background-color: #ffffff;
    padding: 15px 10px;
    .floor + .floor {
      margin-top: 15px;
    }
    .store-logo {
      width: 25px;
      height: 25px;
      border-radius: 50%;
      margin-right: 9px;
    }
    .store-name {
      color: #333333;
      font-size: 14px;
      font-weight: bold;
    }

    .evaluation {
      color: #999999;
      font-size: 12px;
      span {
        margin-right: 5px;
      }
    }
  }

  // 商品图文详情
  .graphic-details {
    background-color: #ffffff;
    .title {
      width: 100%;
      height: 48px;
      line-height: 48px;
      color: #38373d;
      font-size: 16px;
      text-align: center;
    }
    .content {
      font-size: 14px !important;
      /deep/ img {
        width: 100%;
      }
    }
  }

  .footer {
    width: 100%;
    height: 50px;
    .fixed-footer {
      position: fixed;
      height: 50px;
      display: flex;
      background-color: #ffffff;
      width: 100%;
      bottom: 0;
      left: 0;
      z-index: 50;
      text-align: center;
      .action + .action {
        position: relative;
        &::after {
          content: '';
          position: absolute;
          top: 50%;
          left: 0;
          width: 1px;
          height: 24px;
          background-color: #e5e5e5;
          transform: translateY(-50%) scaleX(0.5);
        }
      }
      .action {
        width: 80px;
        height: 100%;
        padding: 7px 0;
        color: #505054;
        font-size: 12px;
        .action-icon {
          width: 22px;
          height: 22px;
          margin: 0 auto 5px auto;
          position: relative;
          img {
            width: 100%;
            height: 100%;
          }
          .tag {
            position: absolute;
            top: -5px;
            right: -10px;
            left: auto;
            background-color: $mainColor;
            color: #ffffff;
            border-radius: 50%;
            width: 18px;
            height: 18px;
            line-height: 18px;
            text-align: center;
          }
        }
      }

      // 按钮
      .btn {
        background-color: $mainColor;
        color: #ffffff;
        line-height: 50px;
        height: 50px;
        font-size: 15px;
        border-radius: 0;
        border-color: $mainColor;
        &.cart-btn {
          background-color: #333333;
          border-color: #333333;
        }
      }
    }
  }
}
</style>
